import { BASE_URL } from "@/api/request";
import { SWEAR_WORD } from "@/const/swearWord.js";
import permision from "@/utils/permission.ts";

// export const Toast = (obj: object) => {
//   /* #ifdef H5 */
//   uni.showToast({
//     icon: "none",
//     title: "身份验证过期,请重新登录",
//     duration: 5000,
//   });
//   /*#endif*/

//   /* #ifdef APP-PLUS-NVUE */
//   plus.nativeUI.toast(

//     `
//     <img src="../../static/dun.png" width="32px" height="32px"></img><br/>
//     <font style="font-size:30px;" color="red">再按一次返回键退出水电费了看手机端菲菱科思旧的发了看手机端菲菱科思京东方了开始打几分离开SDK发链接收到了会计法圣诞快乐封建时代力帆科技</font>
//     `,
//     {
//       icon: "../../static/dun.png",
//       duration: "long",
//       style: "block",
//       align: "center", 
//       verticalAlign: "center",
//       type: "richtext",
//       richTextStyle:{
//         align: "center",
//       }
//     }
//   );
//   /* #endif */
// };

var timesr: any = NaN,
  throttleFlag: boolean;
function throttle(func: Function, wait = 500, immediate = true) {
  if (immediate) {
    if (!throttleFlag) {
      throttleFlag = true;
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === "function" && func();
      timesr = setTimeout(() => {
        throttleFlag = false;
      }, wait);
    }
  } else {
    if (!throttleFlag) {
      throttleFlag = true;
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      timesr = setTimeout(() => {
        throttleFlag = false;
        typeof func === "function" && func();
      }, wait);
    }
  }
}

function _noNet() {
  uni.showToast({
    icon: "none",
    title: "没有网络,请检查",
    duration: 2500,
  });
}

export const noNet = () => {
  throttle(_noNet, 5000, true);
};

export const checkNet = () => {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      async success(res) {
        if (res.networkType === "none") {
          noNet();
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail() {
        resolve(false);
      },
    });
  });
};

export const wait = (time: number) => {
  return new Promise((resolve, reject) => {
    if (!time) {
      resolve(true);
    } else {
      setTimeout(() => {
        resolve(true);
      }, time);
    }
  });
};

let needShowLoading = true;
let startTime = 0;

export const showLoading = (title?: string) => {
  setTimeout(() => {
    if (needShowLoading) {
      startTime = new Date().getTime();
      if (title == null) {
        uni.showLoading();
      } else {
        uni.showLoading({
          title: title,
        });
      }
      setTimeout(() => {
        uni.hideLoading();
      }, 8000);
    }
    needShowLoading = true;
  }, 1000);
};

export const closeLoading = async () => {
  const closeTime = new Date().getTime();
  if (startTime === 0) {
    needShowLoading = false;
    return Promise.resolve(true);
  }

  if (closeTime >= startTime + 800) {
    uni.hideLoading();
    startTime = 0;
    return Promise.resolve(true);
  } else {
    await wait(startTime + 800 - closeTime);
    startTime = 0;
    uni.hideLoading();
    return Promise.resolve(true);
  }
};

export const uploadFile = (filePath: string) => {
  const token = uni.getStorageSync("api_token");
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      header: {
        token,
      },
      url: `${BASE_URL}/file/upload`, //仅为示例，非真实的接口地址
      filePath: filePath,
      name: "file",
      formData: {
        isCompress: 1,
      },
      //formData: {},
      success: (uploadFileRes) => {
        let res: any;

        try {
          res = JSON.parse(uploadFileRes.data);
        } catch (error) {
          reject(error);
        }

        const { flag, data, message } = res;

        if (flag !== 1) {
          reject(message || "上传失败");
        }

        const { fileUrl } = data;

        resolve(fileUrl);
      },
      fail(error) {
        reject(error);
      },
    });
  });
};

export const downloadFile = (download_url: string) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: download_url,
      success(res) {
        const { tempFilePath } = res;
        resolve(tempFilePath);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const saveImg = (tempFilePath: string) => {
  return new Promise((resolve, reject) => {
    uni.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success() {
        resolve(true);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const closeWebview = (path: string) => {
  const pages = getCurrentPages();
  pages.forEach((page: any, index: number) => {
    if (page.route === path) {
      _index = index;
      const webview = page.$getAppWebview();
      setTimeout(() => {
        webview.close("none", 0);
      }, 500);
    }
  });
};

/**
 * 补全网址
 * @param url
 */
export function fixUrl(url: string): string {
  let str =
    url.substr(0, 7).toLowerCase() === "http://" ||
    url.substr(0, 7).toLowerCase() === "https:/"
      ? url
      : "http://" + url;
  return str;
}

export const getAppVersion = () => {
  return new Promise((resolve, reject) => {
    try {
      plus.runtime.getProperty(plus.runtime.appid as string, (wgtinfo) => {
        resolve(wgtinfo.version);
      });
    } catch (e) {
      reject(e);
    }
  });
};

export const getPlatform = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success(result) {
        resolve(result.platform);
      },
      fail(err) {
        reject(err);
      },
    });
  });
};

export const replaceSwear = (str: string) => {
  let backStr = str;
  SWEAR_WORD.forEach((swear: string) => {
    let replaceText = "";
    for (let i = 0; i < swear.length; i++) {
      replaceText += "*";
    }

    if (uni.platform === "ios") {
      backStr = backStr.replaceAll(swear, replaceText);
    } else {
      let reg = new RegExp(swear, "gm");
      backStr = backStr.replace(reg, (str: string) => {
        if (str) {
          let t = "";
          for (let i = 0; i < str.length; i++) {
            t += "*";
          }
          return t;
        } else {
          return "";
        }
      });
    }
  });
  return backStr;
};
export const checkSwear = (str: string, showToast: boolean) => {
  let flag = true;
  for (let i = 0; i < SWEAR_WORD.length; i++) {
    if (str.includes(SWEAR_WORD[i])) {
      flag = false;
      if (showToast) {
        uni.showToast({
          icon: "none",
          title: "您输入的内容包含敏感词，请重新输入",
          duration: 2000,
        });
      }
    }
  }
  return flag;
};

export const chooseImage = (obj: any) => {
  const oldfail = obj.fail;
  obj.fail = (err: any) => {
    console.log("eeeeeeeeeee");
    console.log("eeeeeeeeeee");
    console.log("eeeeeeeeeee");
    console.log(err);
    const { errMsg, code } = err;

    let _index = errMsg.toLowerCase().indexOf("permission");
    if (_index !== -1) {
      if (uni.platform === "ios") {
        uni.showModal({
          title: `无法使用相机`,
          content: "当前无相机使用权限，建议前往系统设置，允许应用访问[相机]",
          showCancel: true,
          confirmText: "前往系统设置",
          cancelText: "取消",
          async success({ confirm, cancel }) {
            if (confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
      }
      if (uni.platform === "android") {
        let name = "相机";
        let str = "相机";

        if (code === 12) {
          name = "相册";
          str = "储存";
        }

        uni.showModal({
          title: `无法使用${name}`,
          content: `当前无${name}使用权限，建议前往权限设置，允许应用访问[${str}]`,
          showCancel: true,
          confirmText: "前往权限设置",
          cancelText: "取消",
          async success({ confirm, cancel }) {
            if (confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
      }
    }

    if (oldfail && typeof oldfail === "function") {
      oldfail(err);
    }
  };
  uni.chooseImage(obj);
};

export const chooseVideo = (obj: any) => {
  const oldfail = obj.fail;
  obj.fail = (err: any) => {
    console.log("eeeeeeeeeee");
    console.log("eeeeeeeeeee");
    console.log("eeeeeeeeeee");
    console.log(err);
    const { errMsg, code } = err;
    let permission_index = errMsg.toLowerCase().indexOf("permission");

    let cammer_index = errMsg.indexOf("filming permission");
    let microphone_index = errMsg.indexOf("microphone permission");
    if (uni.platform === "ios") {
      if (cammer_index !== -1) {
        uni.showModal({
          title: `无法使用相机`,
          content: "当前无相机使用权限，建议前往系统设置，允许应用访问[相机]",
          showCancel: true,
          confirmText: "前往系统设置",
          cancelText: "取消",
          async success({ confirm, cancel }) {
            if (confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
      }
      if (microphone_index !== -1) {
        uni.showModal({
          title: `无法使用麦克风`,
          content:
            "当前无麦克风使用权限，建议前往系统设置，允许应用访问[麦克风]",
          showCancel: true,
          confirmText: "前往系统设置",
          cancelText: "取消",
          async success({ confirm, cancel }) {
            if (confirm) {
              permision.gotoAppPermissionSetting();
            }
          },
        });
      }
    }

    if (uni.platform === "android") {
      if (permission_index !== -1) {
        if (code == 12) {
          uni.showModal({
            title: `无法使用您的视频`,
            content: "当前无视频使用权限，建议前往权限设置，允许应用访问[储存]",
            showCancel: true,
            confirmText: "前往权限设置",
            cancelText: "取消",
            async success({ confirm, cancel }) {
              if (confirm) {
                permision.gotoAppPermissionSetting();
              }
            },
          });
        }
        if (code == 11) {
          uni.showModal({
            title: `无法使用相机`,
            content: "当前无相机使用权限，建议前往权限设置，允许应用访问[相机]",
            showCancel: true,
            confirmText: "前往权限设置",
            cancelText: "取消",
            async success({ confirm, cancel }) {
              if (confirm) {
                permision.gotoAppPermissionSetting();
              }
            },
          });
        }
      }
    }

    if (oldfail && typeof oldfail === "function") {
      oldfail(err);
    }
  };
  uni.chooseVideo(obj);
};
//生成7位随机数
export const generateSevenDigitRandomNumber = () => {  
    // 生成一个介于0和1之间的随机浮点数，然后乘以10000000（7个0）  
    // 这样可以得到一个介于0和9999999之间的随机浮点数  
    let randomFloat = Math.random() * 10000000;  
  
    // 使用Math.floor()函数将浮点数向下取整，得到一个7位的随机整数  
    let randomInt = Math.floor(randomFloat);  
  
    // 如果生成的数字小于1000000（即不是7位），则在前面补0，直到它是7位  
    let sevenDigitNumber = String(randomInt).padStart(7, '0');  
  
    return parseInt(sevenDigitNumber);  
}  